package com.Register.utils;

import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashSet;
import java.util.Set;

public class RedisUtil {

    private static StringRedisTemplate stringRedisTemplate;

    /**
     * 用于删除缓存
     * @param cacheKey
     */
    public static void deleteRedisKey(StringRedisTemplate stringRedisTemplate,String cacheKey){
        //查找符合前缀名的所有缓存
        Set<String> keysToDelete=new HashSet<>();
        Cursor<byte[]> cursor=stringRedisTemplate.getConnectionFactory()
                .getConnection()
                .scan(ScanOptions.scanOptions().match(cacheKey+"*").count(1000).build());
        while (cursor.hasNext()){
            keysToDelete.add(new String(cursor.next()));
        }
        //删除对应的缓存，以免查到脏数据
        if(!keysToDelete.isEmpty()){
            stringRedisTemplate.delete(keysToDelete);
        }
    }
}
